import { myGetRequest,myPostRequest } from "../../utils/myRequest.js"
//index.js
//获取应用实例
const app = getApp()

Page({
  data: {
    motto: 'Hi ！',
    userInfo: {},
    hasUserInfo: false,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    encryptedData: "",
    iv: "",
    sessionId:""
  },

  onLoad: function(options) {
    // Do some initialize when page load.

  },
  onShow: function() {
    // Do something when page show.
    
  },
  onReady: function() {
    // Do something when page ready.
  },
  onHide: function() {
    // Do something when page hide.
    
  },
  onUnload: function() {
    // Do something when page close.
    
  },
  getUserProfile: function(e) {
    const that = this;
    //  获得 encryptedData & iv
    wx.getUserProfile({
      desc: '业务需要',
      success: res => {
        this.setData({ encryptedData: res.encryptedData, iv: res.iv })
        // 获得 sessionId
        wx.login({
          success: async (res) =>{
            const code = res.code;
            if(res.code){
              const res = await myGetRequest({ url: '/weixin/sessionId/' + code })
              if( res.statusCode == 200 ){
                that.setData({ sessionId: res.data })
                const {encryptedData, iv, sessionId} = this.data;
                const res2 = await myPostRequest({ 
                  url: '/weixin/authLogin',
                  data: {
                    "encryptedData": encryptedData,
                    "iv": iv,
                    "sessionId": sessionId
                  }
                })
                
                if( res2.statusCode == 200 && res2.data.code==0){
                  const userInfo = res2.data.data;
                  wx.setStorageSync('userInfo', userInfo);
                  that.setData({
                    userInfo: userInfo,
                    hasUserInfo: true
                  })
                  wx.switchTab({
                    url: '../index/index'
                  })
                }else{
                  console.log(res2.data.message);
                  wx.showToast({
                    title: res2.data.message,
                    icon: 'none',
                    duration:2500

                  })
                }
              }else{
                wx.showToast({
                  title: '网络错误！',
                  icon: 'error',
                  duration:1500
                })
                return;
              }
            }else{
              console.log("获取用户登录状态失败!" + res.errMsg);
            }
          }
        })
      }
    })
  }

})
